package com.fivefox.personnel.enterprise.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fivefox.common.FeiShuHTTPResult;
import com.fivefox.common.authentication.AccessCredentialsTool;
import com.fivefox.personnel.enterprise.IPersonnelEnterprise;
import com.fivefox.common.constant.PersonnelEnterpriseURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 李任起
 * @description: 飞书人事企业版接口实现类
 * @createDate: 2023-06-28 11:46
 */
@Service
public class PersonnelEnterpriseImpl implements IPersonnelEnterprise, PersonnelEnterpriseURL {

    @Autowired
    private AccessCredentialsTool accessCredentialsTool;

    Logger logger = LoggerFactory.getLogger(PersonnelEnterpriseImpl.class);


    /**
     * 查询所有雇佣信息
     */
    @Override
    public List<JSONObject> getBatchEmployeeInfo() {
        /** 列出记录 URL */
        StringBuilder url = new StringBuilder();
        url.append(Batch_Employee_URL);
        url.append("?page_size=500");
        String appAccessToken = accessCredentialsTool.getAppAccessToken();
        List<JSONObject> items = new ArrayList<>();

        /** 获取访问下一页数据的凭证 */
        String pageToken = null;
        /** 当pageToken不为空时继续发起下一次请求 */
        do {
            try {
                /** 只有当pageToken不为空时才携带此查询参数 */
                if (pageToken != null) {
                    url.append("?page_token=" + pageToken);
                }
                String result = HttpRequest.get(url.toString()).header("Bearer " + appAccessToken);
                FeiShuHTTPResult body = JSONObject.parseObject(result, FeiShuHTTPResult.class);
                /** 捕捉接口异常信息 */
                if (body.getCode()!=0){
                    logger.error("发起"+url+"请求时出现异常："+body.getMsg());
                }
                JSONArray resultArray = JSONArray.parse(body.getData().get("items").toString());
                for (Object obj : resultArray) {
                    items.add((JSONObject) obj);
                }
                /** 更新pageToken，使正常请求剩余的数据 */
                pageToken = body.getData().get("page_token").toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        } while (pageToken != null && pageToken.length() > 0);

        return items;
    }
}
